import asyncio
from pathlib import Path

from aiogram import Bot, Dispatcher
from aiogram.fsm.storage.redis import RedisStorage
from fluent.runtime import FluentLocalization, FluentResourceLoader

from recruit_bot.core.config import load_bot_config
from recruit_bot.di import init_dependencies
from recruit_bot.handlers import (
    start_commands,
    created_template,
    created_template_cv,
)
from recruit_bot.middleware.l10n import L10nMiddleware


def set_locale(dp: Dispatcher):
    locales_dir = Path(__file__).parent.joinpath('locales')
    l10n_loader = FluentResourceLoader(str(locales_dir) + '/{locale}')
    l10n = FluentLocalization(['ru'], ['strings.ftl'], l10n_loader)
    dp.update.middleware(L10nMiddleware(l10n))


def get_storage(url: str) -> RedisStorage:
    storage = RedisStorage.from_url(
        url,
        connection_kwargs={'decode_responses': True}
    )
    return storage


async def main():
    bot_config = load_bot_config()
    bot = Bot(token=bot_config.token)
    dp = Dispatcher(storage=get_storage(bot_config.redis))
    dp.include_router(start_commands.router)
    dp.include_router(created_template.router)
    dp.include_router(created_template_cv.router)
    set_locale(dp)
    init_dependencies(dp)

    # TODO: Add launch via webhooks
    try:
        await dp.start_polling(bot)
    finally:
        await bot.session.close()


if __name__ == '__main__':
    asyncio.run(main())
